package com.muki.spider.core;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

import org.springframework.stereotype.Component;

/**
 * 过滤器控制器
 * @author ljh_2017
 *
 */
@Component
public class FilterChain {

	private List<String> profiles = new LinkedList<>();

	/**
	 * 将写入的过滤器注册到profiles中去
	 * @param profile
	 */
	public FilterChain() {
		Properties prop = new Properties();
		InputStream in = FilterChain.class.getResourceAsStream("/conf.properties");
		try {
			prop.load(in);
			String classDrivers = prop.getProperty("uri.prof");
			if(classDrivers.indexOf(',')==-1)
				profiles.add(classDrivers);
			else {
				String[] drivers = classDrivers.split(",");
				for(String driver:drivers) {
					profiles.add(driver);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void FilterLoader(RequestUri request) {
		for(String profile:profiles) {
			try {
				Class<?> cls = Class.forName(profile);
				try {
					UriFilter filter = (UriFilter) cls.newInstance();
					if(request.check()) {
						request.ban();
						filter.init();
						filter.filter(request, this);
						filter.destroy();
					} else
						break;
				} catch (InstantiationException | IllegalAccessException e) {
					e.printStackTrace();
				}
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void doFilter(RequestUri request) {
		request.allow();
	}

}
